package xiegd.study.lambda;

import org.springframework.beans.BeanUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @author zengjia
 * @date 2020/8/20 18:51:21
 */
public class BeanCopyUtils {
    public static <T> T copy(Object source, Class<T> targetClass) {
        if (source == null) {
            return null;
        }

        try {
            // 实例化对象必须有无参公有构造方法
            T target = targetClass.newInstance();
            BeanUtils.copyProperties(source, target);
            return target;
        } catch (Exception e) {
            throw new BeanCopyException("Bean copy error for instance", e);
        }
    }

    public static <T> List<T> copyList(List<?> sourceList, Class<T> targetClass) {


        List<T> targetList = new ArrayList<>();

        for (Object source : sourceList) {
            targetList.add(copy(source, targetClass));
        }

        return targetList;
    }

    public static class BeanCopyException extends RuntimeException {
        private static final long serialVersionUID = 152873897614690397L;

        public BeanCopyException(Throwable cause) {
            super(cause);
        }

        public BeanCopyException(String message, Throwable cause) {
            super(message, cause);
        }
    }
}
